package com.jxwifi.cloud.quickcleanserver.mycenter;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.basicactivity.BasicActivity;
import com.idroid.widget.LoadDialog;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.adapter.PresentationAdapter;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.WithdraApplyBean;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ListUtils;

/**
 * Created by Administrator on 2019/5/24.
 */

public class PresentationActivity extends CleanBasicActivity implements SwipeRefreshLayout.OnRefreshListener{

    @Bind(R.id.srl_my_order_list)
    SwipeRefreshLayout mSrlMyOrderList;
    @Bind(R.id.rv_my_order_list)
    RecyclerView mRvMyOrderList;
    @Bind(R.id.rel_null_data)
    RelativeLayout mRelNullData;

    private PresentationAdapter mAdapter;
    private int mPageIndex = 1;//页数
    private int mLastVisibleItemIndex;//用于记录滑动监听中Item的位置
    private int mTotalNum;//记录接口中的总条数（如果没有返回这个字段也可以不适用）
    private LinearLayoutManager mLayoutManager;
    //表示是否可以上拉刷新.因为APP中上拉刷新没有添加动画效果，在数据加载的时候，会多次请求上拉刷新的判断，导致数据没加载完成前，再次的执行了数据请求方法
    //数据页数是根据请求的次数叠加的，就会出现数据为空的情况，特加这个字段做判断
    private boolean mIsrefresh = true;
    private LoadDialog mLoadDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_presentation);
        ButterKnife.bind(this);
        openEventBus();
        mLoadDialog= new LoadDialog(mBaseContext, "");
        initView();
        onRefresh();
    }

    @OnClick({R.id.rel_img_back_pressed,R.id.tv_null_data_refresh})
    void clickCK(View v){
        switch (v.getId()){
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
            case R.id.tv_null_data_refresh:
                onRefresh();
                break;
        }
    }

    private void initView() {
        mRvMyOrderList.setLayoutManager(mLayoutManager = new LinearLayoutManager(mBaseContext));
        mRvMyOrderList.setAdapter(mAdapter = new PresentationAdapter(mBaseContext));
        mSrlMyOrderList.setColorSchemeColors(0xfffe8026);
        mSrlMyOrderList.setOnRefreshListener(this);
        /**
         * 上拉刷新监听方法（在RecyclerView控件中实现这个方法）
         */
        mRvMyOrderList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE && mLastVisibleItemIndex + 1 == mAdapter.getItemCount() &&
                        mAdapter.getItemCount() < mTotalNum && mIsrefresh) {
                    mIsrefresh = false;
                    onLoadMore();
                }
            }

            /**
             * 监听滑动中的时候Item的位置
             * @param recyclerView
             * @param dx
             * @param dy
             */
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mLastVisibleItemIndex = mLayoutManager.findLastVisibleItemPosition();
            }
        });
    }

    @Override
    public void onRefresh() {
        mPageIndex = 1;
        getList();
    }

    private void onLoadMore() {
        mPageIndex++;
        getList();
    }

    public void getList(){
        mSrlMyOrderList.setRefreshing(true);
        mLoadDialog.show();
        Params params=new Params();
        params.add("limit",20);
        params.add("page",1);
        AuzHttp.get(UrlPool.WITHDRAW_APPLY, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                mSrlMyOrderList.setRefreshing(false);
                mIsrefresh = true;
                //实体类：WithdraApplyBean
                if (code==0){
                    JSONObject obj = JSON.parseObject(data);
                    String str = obj.getString("records");
                    mTotalNum = obj.getInteger("total");
                    List<WithdraApplyBean> mListBean = JSON.parseArray(str, WithdraApplyBean.class);
                    if (ListUtils.isEmpty(mListBean) || mListBean == null) {
                        mRelNullData.setVisibility(View.VISIBLE);
                        mSrlMyOrderList.setVisibility(View.GONE);
                        mAdapter.updata();
                    }else{
                        mRelNullData.setVisibility(View.GONE);
                        mSrlMyOrderList.setVisibility(View.VISIBLE);
                        if (mPageIndex > 1) {
                            mAdapter.addData(mListBean);
                        } else {
                            mAdapter.refresh(mListBean);
                        }
                    }
                }else{
                    PasswordLogin.passwordlogin(mBaseContext,TAG, AccountMgr.gettell(mBaseContext),AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin){
                        getList();
                    }
                }
                mLoadDialog.dismiss();
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                mSrlMyOrderList.setRefreshing(false);
                mIsrefresh = true;
                mLoadDialog.dismiss();
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);

            }
        },TAG);
    }

}
